package com.wutma.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wutma.common.core.constants.Constants;
import com.wutma.common.core.domain.TableDataInfo;
import com.wutma.common.core.domain.dto.PageQueryDTO;
import com.wutma.common.core.utils.ThreadLocalUtil;
import com.wutma.friend.domain.message.vo.MessageTextVO;
import com.wutma.friend.manager.MessageCacheManager;
import com.wutma.friend.mapper.user.UserMessageTextMapper;
import com.wutma.friend.service.question.IUserMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserMessageServiceImpl implements IUserMessageService {

    @Autowired
    private MessageCacheManager messageCacheManager;

    @Autowired
    private UserMessageTextMapper userMessageTextMapper;

    @Override
    public TableDataInfo list(PageQueryDTO pageQueryDTO) {

        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);

        Long total = messageCacheManager.getListSize(userId);
        List<MessageTextVO> messageTextVOList = new ArrayList<>();
        if (total == null || total <= 0) {
            // 进来则表示缓存中竞赛数据不存在，调用返回数据库中的数据
            PageHelper.startPage(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());
            messageTextVOList = userMessageTextMapper.selectMessageList(userId);
            // 同时刷新缓存，重新为缓存录入数据
            messageCacheManager.refreshCache(userId);
            total = new PageInfo<>(messageTextVOList).getTotal();
        }
        else {
            messageTextVOList = messageCacheManager.getMessageTextVOList(pageQueryDTO, userId);
        }
        if (CollectionUtil.isEmpty(messageTextVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(messageTextVOList, total);
    }
}
